package com.atguigu.srb.service.sms.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.guli.common.util.RandomUtils;
import com.atguigu.guli.common.util.RegexValidateUtils;
import com.atguigu.srb.base.dto.SmsDTO;
import com.atguigu.srb.base.exception.SrbException;
import com.atguigu.srb.base.result.ResponseEnum;
import com.atguigu.srb.base.util.HttpUtils;
import com.atguigu.srb.base.util.SrbAssert;
import com.atguigu.srb.service.sms.config.SmsProperties;
import com.atguigu.srb.service.sms.feign.CoreClient;
import com.atguigu.srb.service.sms.service.SmsService;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@EnableConfigurationProperties(SmsProperties.class) //表示当前组件类对象创建时 需要先初始化SmsProperties对象到容器中
public class SmsServiceImpl implements SmsService {
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    CoreClient coreClient;
    @Override
    public void sendSms(String mobile, Integer type) {
        //1、手机号码格式校验：正则表达式
        SrbAssert.assertTrue(RegexValidateUtils.checkCellphone(mobile), ResponseEnum.MOBILE_ERROR);
        //type=1 注册时 校验手机号码是否已经被占用
        if(type==1){
            Map<String, Object> result = coreClient.isUsed(mobile).getData();
            SrbAssert.assertNotTrue(CollectionUtils.isEmpty(result)|| !(Boolean)(result.get("flag"))
                    ,ResponseEnum.MOBILE_EXIST_ERROR);
        }
        //2、手机号码发送频率： 、一天内只能获取5条
        //5分钟内不能重复获取 key
        String timeLimitKey = "sms:limit:" + type + ":" + mobile;
        SrbAssert.assertNotTrue(stringRedisTemplate.hasKey(timeLimitKey),
                ResponseEnum.ALIYUN_SMS_LIMIT_CONTROL_ERROR);
        //一天内只能获取5条 key
        String countLimitKey = "sms:count:" + type + ":" + mobile;
        if(stringRedisTemplate.hasKey(countLimitKey)){
            //存在发送短信的次数：获取次数
            String countStr = stringRedisTemplate.opsForValue().get(countLimitKey);
            SrbAssert.assertNotTrue(Integer.parseInt(countStr)>=5,ResponseEnum.ALIYUN_SMS_DAY_LIMIT_CONTROL_ERROR);
        }else{
            //countLimitKey 次数数据不存在 初始化0，并设置过期时间
            stringRedisTemplate.opsForValue().set(countLimitKey , "0",
                    24,TimeUnit.HOURS);
        }

        //3、生成验证码发送短信
        String code = RandomUtils.getSixBitRandom();
        // sendMessage(mobile, code);
        //4、更新手机号码获取验证码的频率,缓存验证码
        //缓存验证码到redis中:  使用type区分验证码使用的类型
        stringRedisTemplate.opsForValue().set("sms:code:"+type+":"+mobile,code,5,TimeUnit.MINUTES);
        //更新验证码发送的次数:
        // 如果手机号第一次获取验证码increment   次数默认为0+1
        stringRedisTemplate.opsForValue().increment(countLimitKey);
        //用手机号码拼接key 缓存一个过期时间为5分钟的数据
        stringRedisTemplate.opsForValue().set(timeLimitKey, "1" , 5 ,
                TimeUnit.MINUTES);

    }

    @Override
    public void mqSendMsg(SmsDTO smsDto) {
        String mobile = smsDto.getMobile();
        Integer type = smsDto.getType();
        List<String> params = smsDto.getParams();

        //服务器地址
        String host = SmsProperties.HOST;
        //资源路径
        String path = SmsProperties.PATH;
        //请求方式
        String method = SmsProperties.METHOD;
        //在短信平台购买短信服务时的 唯一id
        String appcode = SmsProperties.APPCODE;
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //请求参数：
        Map<String, String> querys = new HashMap<String, String>();
        //一般的短信平台：都是提供 短信模板id
        String content = type + params.toString();
        querys.put("content", content);
        querys.put("mobile", mobile);
        try {
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            String resultJson = EntityUtils.toString(response.getEntity(), "UTF-8");
            Map map = JSON.parseObject(resultJson, Map.class);
            String resultCode = map.get("error_code").toString();
            if(!"0".equals(resultCode)){
                //短信发送失败
                System.out.println("短信发送失败，原因："+ resultJson);
                throw new SrbException(ResponseEnum.ALIYUN_SMS_ERROR);
            }
            //短信发送成功
            System.out.println("短信发送成功:"+resultJson);
        } catch (Exception e) {
//            e.printStackTrace();
//            throw new SrbException(ResponseEnum.ALIYUN_SMS_ERROR);
            System.out.println("短信发送失败，原因："+"假装成功" );

        }

    }

//    @Resource
//    SmsProperties smsProperties;

    //调用第三方接口发送短信的业务方法
    public void sendMessage(String mobile, String code) {
        //服务器地址
        String host = SmsProperties.HOST;
        //资源路径
        String path = SmsProperties.PATH;
        //请求方式
        String method = SmsProperties.METHOD;
        //在短信平台购买短信服务时的 唯一id
        String appcode = SmsProperties.APPCODE;
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //请求参数：
        Map<String, String> querys = new HashMap<String, String>();
        //一般的短信平台：都是提供 短信模板id
        querys.put("content", "【智能云】您的验证码是"+code+"。如非本人操作，请忽略本短信");
        querys.put("mobile", mobile);
        try {
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            String resultJson = EntityUtils.toString(response.getEntity(), "UTF-8");
            Map map = JSON.parseObject(resultJson, Map.class);
            String resultCode = map.get("error_code").toString();
            if(!"0".equals(resultCode)){
                //短信发送失败
                System.out.println("短信发送失败，原因："+ resultJson);
                throw new SrbException(ResponseEnum.ALIYUN_SMS_ERROR);
            }
            //短信发送成功
            System.out.println("短信发送成功:"+resultJson);
        } catch (Exception e) {
//            e.printStackTrace();
            throw new SrbException(ResponseEnum.ALIYUN_SMS_ERROR);
        }
    }
}
